package com.xt.stock.project.common.until;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wzc
 * @Description: token工具类
 * @date 2020/4/19 22:15
 */
public class TokenUtil {

    //默认token有效时长为30天
    private final static long EffectTime = 1000 * 60 * 60 * 24 * 30;

    private TokenUtil(){}

    /**
     * 生成token
     * @return
     */
    public static String generateToken() {
        Map<String,Object> map = new HashMap<>();
        map.put("userId","123");
        JwtBuilder builder = Jwts.builder() // 设置header.setHeaderParam("typ", "JWT")
                .setExpiration(new Date(System.currentTimeMillis() + EffectTime))//设置过期时间
                .setClaims(map)//设置内容
                ;
        String jwt = builder.compact();
        return jwt;
    }

    /**
     * token解析
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Date parseToken(String jwt) throws Exception {
        Date date = Jwts.parser().setSigningKey("111").parseClaimsJws(jwt).getBody().getExpiration();
        return  date;
    }

    public static void main(String[] args) throws Exception {
        String token = TokenUtil.generateToken();
        byte[] bytes = token.getBytes();
        String encoded = Base64.getEncoder().encodeToString(bytes);
        System.out.println("token:"+token);
        System.out.println("encoded:"+encoded);

//        Date date = parseToken(token);
//        System.out.println("过期时间:"+date.getTime());
    }

}
